<template>
  <XenPageLayout
    title="学习经历"
    title-align="left"
    :show-back="true"
    navbar-bg-color="#059669"
    navbar-text-color="#ffffff"
    navbar-icon-color="#ffffff"
    :loading="loading"
    :error="hasError"
    @retry="loadEducationList"
  >
    <view class="page-container">
      <!-- 列表容器 -->
      <view class="list-container">
        <!-- 空状态 -->
        <view v-if="!loading && educationList.length === 0" class="empty-state">
          <view class="empty-icon-container">
            <view class="empty-icon-bg">
              <uni-icons
                type="paperplane"
                size="40"
                color="#059669"
              ></uni-icons>
            </view>
            <view class="empty-decorative-dots">
              <view class="dot dot-1"></view>
              <view class="dot dot-2"></view>
              <view class="dot dot-3"></view>
            </view>
          </view>
          <view class="empty-content">
            <text class="empty-title">暂无学习经历</text>
            <text class="empty-subtitle">该员工还没有录入任何学习经历信息</text>
          </view>
          <view class="empty-illustration">
            <view class="book-stack">
              <view class="book book-1"></view>
              <view class="book book-2"></view>
              <view class="book book-3"></view>
            </view>
          </view>
        </view>

        <!-- 教育经历列表 -->
        <view
          v-for="(item, index) in educationList"
          :key="item.ID"
          class="list-card"
          @click="handleItemClick(item)"
        >
          <!-- 卡片头部 -->
          <view class="card-header">
            <view class="header-content">
              <view class="header-left">
                <text class="card-title">{{ item.School || "" }}</text>
                <text class="card-subtitle">{{ item.Major || "" }}</text>
              </view>
            </view>
          </view>

          <!-- 卡片内容 -->
          <view class="card-content">
            <view class="field-grid">
              <view class="field-item">
                <text class="field-label">学历：</text>
                <text class="field-value">{{
                  item.EducationLevel || "-"
                }}</text>
              </view>
              <view class="field-item">
                <text class="field-label">学制：</text>
                <text class="field-value">{{
                  item.EducationSystem || "-"
                }}</text>
              </view>
              <view class="field-item">
                <text class="field-label">入学日期：</text>
                <text class="field-value">{{
                  formatDate(item.EnrollmentDate)
                }}</text>
              </view>
              <view class="field-item">
                <text class="field-label">毕业日期：</text>
                <text class="field-value">{{
                  formatDate(item.GraduationDate)
                }}</text>
              </view>
            </view>

            <!-- 操作按钮 -->
            <view class="action-buttons">
              <view class="action-button detail" @click.stop="viewDetail(item)">
                <uni-icons type="eye" size="14" color="#6b7280"></uni-icons>
                <text class="action-text">查看详情</text>
              </view>
            </view>
          </view>
        </view>

        <!-- 底部间距 -->
        <view class="bottom-spacing"></view>
      </view>
    </view>
  </XenPageLayout>
</template>

<script lang="ts" setup>
import { ref, onMounted } from "vue";
import XenPageLayout from "@/layouts/XenPageLayout.vue";
import Api from "../api/index";
import type { GetEducationResponse } from "../api/interface";

// 页面数据
const loading = ref(false);
const hasError = ref(false);
const educationList = ref<GetEducationResponse[]>([]);
const personId = ref<string>("");

// 用户信息
const userInfo = ref<any>(null);

// 用户人员信息
const userPersonInfo = ref<any>(null);

// 加载用户人员信息
const loadUserPersonInfo = async () => {
  if (!userInfo.value?.ITCode) {
    hasError.value = true;
    uni.showToast({
      title: "缺少用户信息",
      icon: "none",
    });
    return;
  }

  loading.value = true;
  hasError.value = false;

  try {
    const searchParams = {
      Limit: 50,
      Name: "",
      Page: 1,
      SortInfo: null,
      StaffNo: userInfo.value.ITCode,
      Phone: userInfo.value.Attributes?.CellPhone || "",
    };

    console.log("搜索人员信息参数:", searchParams);
    const res = await Api().search(searchParams);
    console.log("人员信息接口返回:", res);

    if (res && res.Data && Array.isArray(res.Data) && res.Data.length > 0) {
      userPersonInfo.value = res.Data[0];
      personId.value = userPersonInfo.value.ID;
      console.log("获取用户人员信息成功:", userPersonInfo.value);
      // 获取到人员信息后，加载学习经历列表
      await loadEducationList();
    } else {
      hasError.value = true;
      console.log("未找到人员信息，返回数据:", res);
      uni.showToast({
        title: "未找到对应人员信息",
        icon: "none",
      });
    }
  } catch (error) {
    console.error("获取用户人员信息异常:", error);
    hasError.value = true;
    uni.showToast({
      title: "获取人员信息失败",
      icon: "none",
    });
  } finally {
    loading.value = false;
  }
};

// 获取路由参数
onMounted(() => {
  // 从本地存储获取用户信息
  const cachedUserInfo = uni.getStorageSync("userInfo");
  if (cachedUserInfo) {
    userInfo.value = cachedUserInfo;
    console.log("学习经历页面加载用户信息:", cachedUserInfo);
    // 加载人员信息
    loadUserPersonInfo();
  } else {
    loading.value = false;
    hasError.value = true;
    uni.showToast({
      title: "请先登录",
      icon: "none",
    });
    setTimeout(() => {
      uni.navigateBack();
    }, 1500);
  }
});

// 加载教育经历列表
const loadEducationList = async () => {
  if (!personId.value) {
    return;
  }

  try {
    const requestData = {
      Limit: 50,
      Page: 1,
      PersonId: personId.value,
      SortInfo: null,
    };

    console.log("获取教育经历请求参数:", requestData);
    const res = await Api().getEducation(requestData);
    console.log("教育经历接口返回:", res);

    if (res && res.Data && Array.isArray(res.Data)) {
      educationList.value = res.Data;
      console.log("获取教育经历成功:", educationList.value);
    } else {
      educationList.value = [];
      console.log("教育经历数据为空");
    }
  } catch (error) {
    console.error("获取教育经历异常:", error);
    hasError.value = true;
    uni.showToast({
      title: "获取教育经历失败",
      icon: "none",
    });
  } finally {
    loading.value = false;
  }
};

// 格式化日期
const formatDate = (dateStr: string | null | undefined) => {
  if (!dateStr || typeof dateStr !== "string") return "-";
  try {
    const date = new Date(dateStr);
    return `${date.getFullYear()}.${String(date.getMonth() + 1).padStart(
      2,
      "0",
    )}.${String(date.getDate()).padStart(2, "0")}`;
  } catch {
    return dateStr.substring(0, 10).replace(/-/g, ".") || "-";
  }
};

// 处理项目点击
const handleItemClick = (item: GetEducationResponse) => {
  // 点击整个卡片也可以查看详情
  viewDetail(item);
};

// 查看详情
const viewDetail = (item: GetEducationResponse) => {
  console.log("查看教育经历详情:", item);

  // 跳转到详情页面，注意路径要从 pages 开始
  uni.navigateTo({
    url: `/subpkg-hr/hr/employee/education-detail?id=${item.ID}`,
  });
};

// 编辑项目
const editItem = (item: GetEducationResponse) => {
  console.log("编辑教育经历:", item);
  // TODO: 跳转到编辑页面
  uni.showToast({
    title: "编辑功能开发中",
    icon: "none",
  });
};

// 删除项目
const deleteItem = (item: GetEducationResponse) => {
  console.log("删除教育经历:", item);
  uni.showModal({
    title: "确认删除",
    content: `确定要删除"${item.School}"的学习经历吗？`,
    success: (res) => {
      if (res.confirm) {
        // TODO: 调用删除接口
        uni.showToast({
          title: "删除功能开发中",
          icon: "none",
        });
      }
    },
  });
};

// 新增教育经历
const addNewEducation = () => {
  console.log("新增教育经历");
  // TODO: 跳转到新增页面
  uni.showToast({
    title: "新增功能开发中",
    icon: "none",
  });
};
</script>

<style lang="scss" scoped>
.page-container {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  max-width: 448px;
  margin: 0 auto;
  background: white;
  position: relative;
}

.list-container {
  flex: 1;
  background: transparent;
  padding: 24px 16px;
  overflow-y: auto;

  .empty-state {
    text-align: center;
    padding: 80px 20px;
    position: relative;
    min-height: 400px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;

    .empty-icon-container {
      position: relative;
      margin-bottom: 32px;

      .empty-icon-bg {
        width: 80px;
        height: 80px;
        background: linear-gradient(
          135deg,
          rgba(5, 150, 105, 0.1),
          rgba(16, 185, 129, 0.1)
        );
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        position: relative;
        box-shadow: 0 8px 32px rgba(5, 150, 105, 0.2);
        animation: pulse 2s infinite;
      }

      .empty-decorative-dots {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        width: 120px;
        height: 120px;

        .dot {
          position: absolute;
          width: 6px;
          height: 6px;
          background: #059669;
          border-radius: 50%;
          opacity: 0.6;
          animation: float 3s ease-in-out infinite;

          &.dot-1 {
            top: 10px;
            right: 20px;
            animation-delay: 0s;
          }

          &.dot-2 {
            bottom: 15px;
            left: 15px;
            animation-delay: 1s;
          }

          &.dot-3 {
            top: 20px;
            left: 10px;
            animation-delay: 2s;
          }
        }
      }
    }

    .empty-content {
      margin-bottom: 40px;

      .empty-title {
        display: block;
        font-size: 20px;
        font-weight: 600;
        color: #374151;
        margin-bottom: 8px;
        line-height: 1.4;
      }

      .empty-subtitle {
        display: block;
        font-size: 14px;
        color: #6b7280;
        line-height: 1.5;
        max-width: 280px;
      }
    }

    .empty-illustration {
      .book-stack {
        position: relative;
        width: 60px;
        height: 45px;
        margin: 0 auto;

        .book {
          position: absolute;
          width: 50px;
          height: 8px;
          border-radius: 2px;
          box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

          &.book-1 {
            background: linear-gradient(135deg, #059669, #10b981);
            bottom: 0;
            left: 0;
            transform: rotate(-2deg);
          }

          &.book-2 {
            background: linear-gradient(135deg, #3b82f6, #60a5fa);
            bottom: 8px;
            left: 5px;
            transform: rotate(1deg);
          }

          &.book-3 {
            background: linear-gradient(135deg, #f59e0b, #fbbf24);
            bottom: 16px;
            left: 2px;
            transform: rotate(-1deg);
          }
        }
      }
    }
  }

  @keyframes pulse {
    0%,
    100% {
      transform: scale(1);
    }
    50% {
      transform: scale(1.05);
    }
  }

  @keyframes float {
    0%,
    100% {
      transform: translateY(0px);
      opacity: 0.6;
    }
    50% {
      transform: translateY(-8px);
      opacity: 1;
    }
  }

  .list-card {
    background: white;
    border-radius: 12px;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    margin-bottom: 16px;
    overflow: hidden;
    transition: all 0.3s ease;

    &:active {
      transform: translateY(-2px);
      box-shadow: 0 8px 15px rgba(0, 0, 0, 0.15);
    }

    .card-header {
      background: linear-gradient(135deg, #059669, #10b981);
      color: white;
      padding: 16px;
      position: relative;

      .header-content {
        display: flex;
        align-items: flex-start;
        justify-content: space-between;

        .header-left {
          flex: 1;

          .card-title {
            display: block;
            color: white;
            font-size: 18px;
            font-weight: bold;
            line-height: 1.4;
            margin-bottom: 4px;
          }

          .card-subtitle {
            display: block;
            color: rgba(255, 255, 255, 0.9);
            font-size: 14px;
            line-height: 1.4;
          }
        }
      }
    }

    .card-content {
      padding: 16px;

      .field-grid {
        display: flex;
        flex-direction: column;
        gap: 8px;
        font-size: 14px;
        margin-bottom: 12px;

        .field-item {
          display: flex;
          justify-content: space-between;
          align-items: flex-start;
          padding: 6px 0;
          border-bottom: 1px solid #f3f4f6;

          &:last-child {
            border-bottom: none;
          }

          .field-label {
            color: #6b7280;
            min-width: 80px;
            flex-shrink: 0;
            margin-right: 12px;
            font-weight: 500;
          }

          .field-value {
            font-weight: 500;
            text-align: right;
            word-break: break-word;
            flex: 1;
            color: #374151;
          }
        }
      }

      .action-buttons {
        display: flex;
        justify-content: flex-end;
        gap: 8px;
        padding-top: 12px;
        border-top: 1px solid #f1f5f9;

        .action-button {
          display: flex;
          align-items: center;
          gap: 4px;
          font-size: 14px;
          cursor: pointer;
          transition: all 0.2s ease;

          .action-text {
            font-size: 14px;
            font-weight: 500;
          }

          &.detail {
            color: #6b7280;

            .action-text {
              color: #6b7280;
            }

            &:active {
              opacity: 0.7;
            }
          }
        }
      }
    }
  }

  .bottom-spacing {
    height: 32px;
  }
}
</style>
